package com.org.oracle.helper;

import com.org.oracle.enums.ResponseCodeEnum;
import com.org.oracle.exception.CustomException;
import com.org.oracle.properties.EmailProperties;
import jakarta.annotation.Resource;
import jakarta.mail.internet.InternetAddress;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Date;

/**
 * @author: heiye
 * @date: 2024/12/03 下午7:55
 * @version: v1.0.0
 * @description:
 */
@Slf4j
@Component
public class EmailHelper {

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private EmailProperties emailProperties;

    @Resource
    private TemplateEngine templateEngine;

    @SneakyThrows
    public void sendEmail(String email, String code, String timeout) {
        // 构建Helper
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
        // 邮件发信人
        mimeMessageHelper.setFrom(new InternetAddress("小研书<" + emailProperties.getUsername() + ">"));
        // 邮件收信人
        mimeMessageHelper.setTo(email);
        // 邮件主题
        mimeMessageHelper.setSubject("非常感谢您使用本产品喵~~~");
        // 邮件发送时间
        mimeMessageHelper.setSentDate(new Date());
        // 邮件内容
        Context context = new Context();
        // 数据渲染准备
        context.setVariable("code", code);
        context.setVariable("timeout", timeout + "分钟");
        // 数据渲染
        String emailTemplates = templateEngine.process("emailTemplates", context);
        // html 发送邮件
        mimeMessageHelper.setText(emailTemplates, true);

        try {
            log.info("==> 开始邮件发送, email: {}, code: {}", email, code);

            javaMailSender.send(mimeMessageHelper.getMimeMessage());

            log.info("==> 邮件发送成功");
        } catch (Exception e) {
            log.error("==> 邮件发送错误: ", e);
            throw new CustomException(ResponseCodeEnum.SERVER_ERROR);
        }
    }
}
